package com.ewanghuiju.app.ui.pintuan.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.pintuan.PintuanSureOrderContract;
import com.ewanghuiju.app.component.ImageLoader;
import com.ewanghuiju.app.component.RxBus;
import com.ewanghuiju.app.model.bean.request.PtistarGroupBean;
import com.ewanghuiju.app.model.bean.response.AddressListResponBean;
import com.ewanghuiju.app.model.bean.response.PintuanShopListResponBean;
import com.ewanghuiju.app.model.bean.response.RuleBean;
import com.ewanghuiju.app.model.event.SendEvent;
import com.ewanghuiju.app.model.http.response.BaseResponse;
import com.ewanghuiju.app.presenter.pintuan.PintuanSureOrderPresenter;
import com.ewanghuiju.app.ui.my.activity.ChangeBodyWithCodeActivity;
import com.ewanghuiju.app.ui.my.activity.ShopAddressListActivity;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.MD5Util;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.StringUtil;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.ewanghuiju.app.widget.SwitchButton;
import com.ewanghuiju.app.widget.popupwindow.CustomBasePopup;
import com.ewanghuiju.app.widget.popupwindow.PswKeyboardPopup;
import com.ewanghuiju.app.widget.pswkeyboard.OnPasswordInputFinish;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.muddzdev.styleabletoast.StyleableToast;

import androidx.cardview.widget.CardView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author sj  qq:751943509
 * @class 确认订单
 * @time 2020/2/19
 */
public class PintuanSureOrderActivity extends BaseActivity<PintuanSureOrderPresenter> implements PintuanSureOrderContract.View {
    @BindView(R.id.iv_position)
    ImageView ivPosition;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.layout_address)
    LinearLayout layoutAddress;
    @BindView(R.id.rv_shop)
    RoundedImageView rvShop;
    @BindView(R.id.tv_order_title)
    TextView tvOrderTitle;
    @BindView(R.id.tv_order_guige)
    TextView tvOrderGuige;
    @BindView(R.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R.id.tv_order_yunfei)
    TextView tvOrderYunfei;
    @BindView(R.id.tv_order_paymoney)
    TextView tvOrderPaymoney;
    @BindView(R.id.tv_order_topay)
    TextView tvOrderTopay;
    @BindView(R.id.tv_spe_price)
    TextView tvSpePrice;
    @BindView(R.id.tv_address_text)
    TextView tvAddressText;
    @BindView(R.id.layout_address_phone)
    LinearLayout layoutAddressPhone;
    @BindView(R.id.tv_default)
    TextView tvDefault;
    //团长是否拼中
    @BindView(R.id.switchButton)
    SwitchButton switchButton;
    @BindView(R.id.cv_is_goods)
    CardView cvIsGoods;
    //订单备注
    @BindView(R.id.et_order_remarks)
    EditText etOrderRemarks;

    private PintuanShopListResponBean pintuanShopListResponBean;
    private AddressListResponBean addressListResponBean;
    private String specsId;
    private String specsText;
    private String group_id;

    private Animation showAnimation, dismissAnimation;

    private boolean isDebug = false;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_pintuan_sure_order;
    }

    @Override
    protected void initEventAndData() {
        pintuanShopListResponBean = (PintuanShopListResponBean) getIntent().getSerializableExtra(Constants.PINTUAN_SURE_ORDER_INFO);
        addressListResponBean = (AddressListResponBean) getIntent().getSerializableExtra(Constants.PINTUAN_ADDRESS_INFO);

        specsId = getIntent().getStringExtra(Constants.PINTUAN_SPECSID);
        specsText = getIntent().getStringExtra(Constants.PINTUAN_SPECS_TEXT);
        group_id = getIntent().getStringExtra(Constants.PINTUAN_GROUP_ID);
        if (pintuanShopListResponBean != null) {
            tvOrderTitle.setText(pintuanShopListResponBean.getGoods_name());
            tvSpePrice.setText(pintuanShopListResponBean.getSpe_price());
            tvOrderPaymoney.setText(pintuanShopListResponBean.getSpe_price());
            ImageLoader.load(mContext, pintuanShopListResponBean.getImage(), rvShop);
            if (pintuanShopListResponBean.getIs_free() == 0) {
                tvOrderYunfei.setText("免运费");
            } else {
                tvOrderYunfei.setText(pintuanShopListResponBean.getPostage());
            }
        }
        tvOrderGuige.setText(TextUtils.isEmpty(specsText) ? "" : specsText);
        if (addressListResponBean != null && !TextUtils.isEmpty(addressListResponBean.getMobile())) {
            layoutAddressPhone.setVisibility(View.VISIBLE);
            tvOrderName.setText(addressListResponBean.getName());
            tvOrderNumber.setText(addressListResponBean.getMobile());
            tvAddressText.setText("地址：" + addressListResponBean.getProvince() + addressListResponBean.getCity() + addressListResponBean.getCountry() + addressListResponBean.getDetail());
            tvDefault.setVisibility(addressListResponBean.getIs_default() == 1 ? View.VISIBLE : View.GONE);
        } else {
            layoutAddressPhone.setVisibility(View.GONE);
            tvAddressText.setText("请选择收货地址");
        }
        if (TextUtils.isEmpty(group_id)) {
            cvIsGoods.setVisibility(View.VISIBLE);
        }

        etOrderRemarks.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString()) && s.toString().length() >= 30) {
                    StyleableToast.makeText(mContext, "备注不能超过30字", Toast.LENGTH_SHORT, R.style.mytoast).show();
                }
            }
        });
    }

    @Override
    public void showContent(String list) {

    }

    @Override
    public void showMoreContent(String list) {

    }

    @Override
    public void showSelectedAddress(AddressListResponBean mAddressListResponBean) {
        if (mAddressListResponBean != null) {
            addressListResponBean = mAddressListResponBean;
            layoutAddressPhone.setVisibility(View.VISIBLE);
            tvDefault.setVisibility(addressListResponBean.getIs_default() == 1 ? View.VISIBLE : View.GONE);
            tvOrderName.setText(mAddressListResponBean.getName());
            tvOrderNumber.setText(mAddressListResponBean.getMobile());
            tvAddressText.setText("地址：" + mAddressListResponBean.getProvince() + mAddressListResponBean.getCity() + mAddressListResponBean.getCountry() + mAddressListResponBean.getDetail());
        }
    }

    @Override
    public void showPay(BaseResponse baseResponse) {
        LoadingDialogUtils.dismissDialog_ios();
        //通知更新   刷新用户信息
        RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_USERINFO));
        //刷新商品信息
        RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_SHOP_INFO));
        //刷新列表
        RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_GROUP_INFO));
        //支付完成
//        new StartActivityUtil(mContext, PintuanOrderDetailsActivity.class)
//                .putExtra(Constants.PINTUANORDER_FROM, Constants.PINTUANORDER_FROM_CREATE_ORDER)
//                .putExtra(Constants.PINTUANORDER_NO, baseResponse.getId())
//                .startActivity(false);

        new StartActivityUtil(mContext, PintuanDetailsActivity.class)
                .putExtra(Constants.PINTUAN_GROUP_ID, baseResponse.getGroup_id() + "")
                .startActivity(false);

        super.onBackPressedSupport();
        slideRightIn();
    }

    @Override
    public void showPayError(int code, String msg) {
        //实付失败
        if (code == 100) {
            super.onBackPressedSupport();
        }
    }

    @Override
    public void isbindPwd() {
        //绑定成功
        if(isDebug){
            String md5Pwd = MD5Util.getMD5(MD5Util.getMD5("123456"));
            PtistarGroupBean ptistarGroupBean = new PtistarGroupBean();
            ptistarGroupBean.setGoods_id(pintuanShopListResponBean.getId() + "");
            ptistarGroupBean.setSpecs_id(TextUtils.isEmpty(specsId) ? "" : specsId);
            ptistarGroupBean.setAddress_id(addressListResponBean.getId() + "");
            ptistarGroupBean.setActual_payment(pintuanShopListResponBean.getSpe_price());
            ptistarGroupBean.setIs_goods(switchButton.isChecked() ? "1" : "0");
            ptistarGroupBean.setPay_password(md5Pwd);//设置支付密码
            ptistarGroupBean.setOrder_remark("");
            LoadingDialogUtils.show(mContext);
            if (TextUtils.isEmpty(group_id)) {
                mPresenter.nowPay(ptistarGroupBean);
            } else {
                ptistarGroupBean.setGroup_id(group_id);
                mPresenter.ptijoinGroup(ptistarGroupBean);
            }
            return;
        }

        PswKeyboardPopup pswKeyboardPopup = new PswKeyboardPopup(mContext);
        pswKeyboardPopup.setPopupGravity(Gravity.BOTTOM);
        pswKeyboardPopup.setOnFinishInput(new OnPasswordInputFinish() {
            @Override
            public void inputFinish(String password) {
                pswKeyboardPopup.dismiss();
                if (!StringUtil.isInteger(password)) {
                    StyleableToast.makeText(mContext, "密码输入格式错误", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    pswKeyboardPopup.dismiss();
                    return;
                }
                String orderRemarks = etOrderRemarks.getText().toString();
                String md5Pwd = MD5Util.getMD5(MD5Util.getMD5(password));
                PtistarGroupBean ptistarGroupBean = new PtistarGroupBean();
                ptistarGroupBean.setGoods_id(pintuanShopListResponBean.getId() + "");
                ptistarGroupBean.setSpecs_id(TextUtils.isEmpty(specsId) ? "" : specsId);
                ptistarGroupBean.setAddress_id(addressListResponBean.getId() + "");
                ptistarGroupBean.setActual_payment(pintuanShopListResponBean.getSpe_price());
                ptistarGroupBean.setIs_goods(switchButton.isChecked() ? "1" : "0");
                ptistarGroupBean.setPay_password(md5Pwd);//设置支付密码
                ptistarGroupBean.setOrder_remark(TextUtils.isEmpty(orderRemarks) ? "" : orderRemarks);
                LoadingDialogUtils.show(mContext);
                if (TextUtils.isEmpty(group_id)) {
                    mPresenter.nowPay(ptistarGroupBean);
                } else {
                    ptistarGroupBean.setGroup_id(group_id);
                    mPresenter.ptijoinGroup(ptistarGroupBean);
                }
            }
        });

        //弹框执行动画
        float fromX = 0;
        float fromY = 1f;
        float toX = 0;
        float toY = 0;
        showAnimation = createTranslateAnimation(fromX, toX, fromY, toY);
        dismissAnimation = createTranslateAnimation(toX, fromX, toY, fromY);

        pswKeyboardPopup.setShowAnimation(showAnimation);
        pswKeyboardPopup.setDismissAnimation(dismissAnimation);

        pswKeyboardPopup.showPopupWindow();
    }

    private CustomBasePopup customBasePopup;

    @Override
    public void nobindPwd() {
        //未绑定支付密码
        if (customBasePopup != null) {
            customBasePopup.showPopupWindow();
            return;
        }
        customBasePopup = new CustomBasePopup(mContext, "前往设置支付密码？", "", "",
                new CustomBasePopup.PopupWindowCallback() {
                    @Override
                    public void sureClickCallback() {
                        new StartActivityUtil(mContext, ChangeBodyWithCodeActivity.class).putExtra(Constants.SETTING_TYPE, 2)
                                .startActivity(true);
                    }

                    @Override
                    public void cancelClickCallback() {

                    }
                });
        customBasePopup.setPopupGravity(Gravity.CENTER);
        customBasePopup.showPopupWindow();
    }

    @Override
    public void showPtiguize(RuleBean bean) {
        //获取规则成功
        LoadingDialogUtils.dismissDialog_ios();
        if (bean == null) {
            StyleableToast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        new StartActivityUtil(mContext, PintuanRuleActivity.class)
                .putExtra(Constants.RULE_TITLE, bean.getIntroduce())
                .putExtra(Constants.RULE_CONTENT, bean.getContent())
                .startActivity(true);
    }

    @OnClick({R.id.tv_order_topay, R.id.layout_address_main, R.id.layout_liucheng})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
        switch (view.getId()) {
            case R.id.tv_order_topay:
                //立即支付
                if (pintuanShopListResponBean == null) {
                    StyleableToast.makeText(mContext, "商品信息出错", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                if (addressListResponBean == null || addressListResponBean.getId() < 0) {
                    StyleableToast.makeText(mContext, "请选择地址", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }

                mPresenter.getIsbindPwd();

                break;
            case R.id.layout_address_main:
                new StartActivityUtil(mContext, ShopAddressListActivity.class).putExtra(Constants.TO_ADDRESS_LIST_TYPE, 2)
                        .startActivity(true);
                break;
            case R.id.layout_liucheng:
                //拼团规则
                LoadingDialogUtils.show(mContext);
                mPresenter.getPtiguize("1");
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {

        CustomBasePopup customBasePopup = new CustomBasePopup(mContext, "确认要放弃付款吗？", "继续支付", "暂时放弃",
                new CustomBasePopup.PopupWindowCallback() {
                    @Override
                    public void sureClickCallback() {
                    }

                    @Override
                    public void cancelClickCallback() {
                        PintuanSureOrderActivity.super.onBackPressedSupport();
                    }
                });
        customBasePopup.setPopupGravity(Gravity.CENTER);
        customBasePopup.showPopupWindow();
    }

    @Override
    protected int getTitleIntText() {
        return R.string.sure_order;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).titleBar(mToolbar)
                .statusBarDarkFont(true)
                .init();
    }
}
